package com.skivingcloud.admin.sys.controller;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.skivingcloud.admin.constants.Constant;
import com.skivingcloud.admin.security.SecurityUser;
import com.skivingcloud.admin.security.UserUtil;
import com.skivingcloud.admin.sys.entity.SysMenu;
import com.skivingcloud.admin.sys.entity.SysStation;
import com.skivingcloud.admin.sys.entity.SysStationMenu;
import com.skivingcloud.admin.sys.service.SysMenuService;
import com.skivingcloud.admin.sys.service.SysStationMenuService;
import com.skivingcloud.admin.sys.service.SysStationService;
import com.skivingcloud.common.utils.PageParameter;
import com.skivingcloud.common.utils.ReturnT;
import com.skivingcloud.common.utils.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.*;

/**
 *  控制层。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Tag(name = "SysStationController", description = "岗位管理API")
@RestController
@RequestMapping("/sysStation/")
public class SysStationController {
    private static final Logger log = LoggerFactory.getLogger(SysStationController.class);
    @Resource
    private SysStationService sysStationService;
    @Resource
    private SysStationMenuService sysStationMenuService;
    @Resource
    private SysMenuService sysMenuService;
    /**
     * 添加。
     *
     * @param sysStation 岗位
     * @return {@code 0} 添加成功，{@code 500} 添加失败
     */
    @Operation(summary = "新增岗位", description = "新增岗位")
    @ApiResponse(responseCode = "2xx",description = "新增岗位")
    @PostMapping("save")
    public ReturnT<Boolean> save(@Validated @RequestBody SysStation sysStation) {
        try{
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysStation::getStationCode).eq(sysStation.getStationCode());
            boolean exists = sysStationService.exists(queryWrapper);
            if(exists){
                return ReturnT.error("岗位编号重复！");
            }
            sysStation.setId(UuidUtil.get32UUID());
            sysStation.setCreater(UserUtil.getCurrentUser().getId());
            sysStation.setCreateTime(LocalDateTime.now());
            return ReturnT.ok(sysStationService.saveHasRes(sysStation));
        }catch(Exception e){
            log.error("保存岗位失败", e);
            return ReturnT.error("保存岗位失败！");
        }
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code 0} 删除成功，{@code 500} 删除失败
     */
    @Operation(summary = "删除岗位", description = "删除岗位")
    @ApiResponse(responseCode = "2xx",description = "删除岗位")
    @GetMapping("remove/{id}")
    public ReturnT<Boolean> remove(@PathVariable("id") Serializable id) {
        try{
            return ReturnT.ok(sysStationService.deleteById(id));
        }catch(Exception e){
            log.error("删除岗位失败", e);
            return ReturnT.error("删除岗位失败！");
        }
    }

    /**
     * 根据主键更新。
     *
     * @param sysStation 岗位信息
     * @return {@code 0} 更新成功，{@code 500} 更新失败
     */
    @Operation(summary = "修改岗位", description = "修改岗位")
    @ApiResponse(responseCode = "2xx",description = "修改岗位")
    @PostMapping("update")
    public ReturnT<Boolean> update(@Validated @RequestBody SysStation sysStation) {
        try{
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysStation::getStationCode).eq(sysStation.getStationCode())
                    .and(SysStation::getId).ne(sysStation.getId());
            boolean exists = sysStationService.exists(queryWrapper);
            if(exists){
                return ReturnT.error("岗位编号重复！");
            }
            sysStation.setModUser(UserUtil.getCurrentUser().getId());
            sysStation.setModTime(LocalDateTime.now());
            return ReturnT.ok(sysStationService.updateByIdHasRes(sysStation));
        }catch(Exception e){
            log.error("保存岗位失败", e);
            return ReturnT.error("保存岗位失败！");
        }
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @Operation(summary = "根据主键获取岗位", description = "根据主键获取岗位")
    @ApiResponse(responseCode = "2xx",description = "根据主键获取岗位")
    @GetMapping("getInfo/{id}")
    public ReturnT<SysStation> getInfo(@PathVariable("id") Serializable id) {
        return ReturnT.ok(sysStationService.getById(id));
    }

    /**
     * 分页查询。
     *
     * @param parameter 分页对象
     * @return 分页对象
     */
    @Operation(summary = "分页查询岗位", description = "分页查询岗位")
    @ApiResponse(responseCode = "2xx",description = "分页查询岗位")
    @PostMapping("page")
    public ReturnT<Page<SysStation>> page(@RequestBody PageParameter<SysStation> parameter) {
        return ReturnT.ok(sysStationService.queryByPage(parameter));
    }
    
    /**
     * 获取岗位资源树，如果不是超级管理员只返回自己租户的资源
     *
     * @param params {tenant:'租户id', id:'岗位id'}
     * @return 岗位资源权限
     */
    @Operation(summary = "获取岗位资源树", description = "获取岗位资源树")
    @ApiResponse(responseCode = "2xx",description = "获取岗位资源树")
    @PostMapping("getTenantStationResTree")
    public ReturnT<Map<String, Object>> getTenantStationResTree(@RequestBody Map<String, Object> params) {
        SecurityUser user = UserUtil.getCurrentUser();
        String tenantId = params.get("tenantId") == null ? null : params.get("tenantId").toString();
        if (!user.getTenantId().equals(Constant.SUPER_ADMIN_TENANT_ID)) {
            tenantId = user.getTenantId();
        }
        if (tenantId == null) {
            return ReturnT.error("租户不明确没数据");
        }
        List<SysMenu> list = sysMenuService.getTenantMenuList(tenantId);
        List<SysStationMenu> asingRes = new ArrayList<>();
        if (params.get("id") != null && !"".equals(params.get("id"))) {
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where(SysStationMenu::getStationId).eq(params.get("id").toString());
            asingRes =sysStationMenuService.list(queryWrapper);
        }
        Map<String, Object> res = new HashMap<>();
        res.put("tree", list);
        res.put("asingRes", asingRes);
        return ReturnT.ok(res);
    }
    
    @Operation(summary = "删除岗位", description = "删除岗位",
            parameters = {@Parameter(name = "ids", description = "岗位id")})
    @ApiResponse(responseCode = "2xx",description = "删除岗位")
    @PostMapping("delete")
    public ReturnT<String> delete(@RequestBody String[] ids){
        try{
            sysStationService.deleteBatch(ids);
            return ReturnT.ok("删除岗位成功");
        }catch(Exception e){
            log.error("删除岗位失败", e);
            return ReturnT.error("删除岗位失败");
        }
    }
    
    /**
     * 删除岗位的资源权限
     * @param ids 岗位id
     * @return 结果
     */
    @Operation(summary = "删除岗位资源权限", description = "删除岗位资源权限",
            parameters = {@Parameter(name = "ids", description = "岗位id")})
    @ApiResponse(responseCode = "2xx",description = "删除岗位资源权限")
    @PostMapping("deleteStationRes")
    public ReturnT<String> deleteStationRes(@RequestBody String[] ids) {
        try {
            QueryWrapper queryWrapper = QueryWrapper.create()
                            .where(SysStationMenu::getStationId).in(Arrays.stream(ids).toList());
            sysStationMenuService.remove(queryWrapper);
            return ReturnT.ok();
        } catch (Exception e) {
            log.error("删除岗位资源权限失败", e);
            return ReturnT.error("删除岗位资源权限失败");
        }
    }
    
    /**
     * 设置岗位资源权限
     * @param station 岗位资源信息
     * @return 结果
     */
    @PostMapping("saveStationRes")
    @Operation(summary="设置岗位资源权限")
    public ReturnT<String> saveStationRes(@RequestBody SysStation station) {
        try {
            sysStationService.saveStationRes(station.getId(), station.getResId());
            return ReturnT.ok();
        } catch (Exception e) {
            log.error("设置资源权限失败", e);
            return ReturnT.error("设置资源权限失败");
        }
    }
}
